﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;

namespace ControlesAWIL
{
    public partial class VentanaBuscador : Form
    {
        public Boolean ok = false;
        public String textoRetorno = string.Empty;
        public String textoDescripcion = string.Empty;

        private BindingSource bindingSource = null;
        //private List<DataGridViewColumn> columnas = new List<DataGridViewColumn>();
        private string ocultarColumnas = string.Empty;
        private string columnaRetorno = string.Empty;
        private string columnaDescripcion = string.Empty;

        public VentanaBuscador()
        {
            InitializeComponent();
        }

        public string ColumnaRetorno
        {
            get { return columnaRetorno; }
            set
            {
                if (value == string.Empty)
                {
                    columnaRetorno = "Id";
                }
                else
                {
                    columnaRetorno = value;
                }
            }
        }

        public bool inicializarVentana(BindingSource bindingSource, string ocultarColumnas, string columnaRetorno, string columnaDescripcion)
        {
            this.ok = false;
            int numeroColumnasVisibles = 0;
            this.bindingSource = bindingSource;
            this.ocultarColumnas = "," + ocultarColumnas.Replace(" ", "").ToUpper() + ",";
            this.columnaRetorno = columnaRetorno;
            this.columnaDescripcion = columnaDescripcion;

            this.LimpiarToolStripButton_Click(null, null);
            

            if (this.bindingSource == null)
            {
                MessageBox.Show("No ha definido la propiedad \"BindingSource\" del buscador");
                return false;
            }

            this.Cursor = Cursors.WaitCursor;
            this.ventanaBuscadorDataGridView.DataSource = bindingSource;
            this.ventanaBuscadorbindingNavigator.BindingSource = bindingSource;

            //-- Cambio el ancho de las columnas deacuerdo al tipo de dato de la misma
            DataTable table = ((DataSet)bindingSource.DataSource).Tables[bindingSource.DataMember];
            string dataType = string.Empty;

            foreach (DataGridViewColumn col in this.ventanaBuscadorDataGridView.Columns)
            {
                dataType = table.Columns[col.Name].DataType.Name;
                if (dataType.Equals("Int16") || dataType.Equals("Int32") || dataType.Equals("Int64") || dataType.Equals("Decimal") || dataType.Equals("Double"))
                {
                    col.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                }
                else if (dataType.Equals("Boolean")) 
                {
                    col.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;                     
                }
            }
            


            //-- Oculto las columnas que corresponden
            if (!this.ocultarColumnas.Trim().Equals(string.Empty))
            {
                foreach (DataGridViewColumn col in this.ventanaBuscadorDataGridView.Columns)
                {
                    if (this.ocultarColumnas.Contains("," + col.Name.ToString().ToUpper() + ","))
                    {
                        col.Visible = false;
                    }
                    else
                    {
                        numeroColumnasVisibles++;
                    }
                }
            }
            this.Cursor = Cursors.Default;
            this.BuscarToolStripTextBox.Focus();

            this.ventanaBuscadorDataGridView.AutoSizeColumnsMode = (numeroColumnasVisibles <= 7 ? DataGridViewAutoSizeColumnsMode.Fill : DataGridViewAutoSizeColumnsMode.None);

            //-- Ordenar por la columna de retorno
            try { this.ventanaBuscadorDataGridView.Sort(this.ventanaBuscadorDataGridView.Columns[this.columnaRetorno], ListSortDirection.Descending); }
            catch (Exception) { }

            return true;
        }

        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)// && this.msTextBox.Text.Trim() != "")
            {
                this.BuscarToolStripTextBox.Focus();
                this.devolverResultado();
            }
            else if (e.KeyCode == Keys.Escape)// && this.msTextBox.Text.Trim() != "")
            {
                this.BuscarToolStripTextBox.Focus();
                this.Close();
            }
            //if (this.ActiveControl != this.BuscarToolStripTextBox.Control)
            //{
            //    this.BuscarToolStripTextBox.Focus();
            //    //this.BuscarToolStripTextBox.Text = this.BuscarToolStripTextBox.Text.Trim() + e.KeyCode.ToString();                
            //}
        }

        private void BuscarToolStripTextBox_TextChanged(object sender, EventArgs e)
        {

            Cursor.Current = Cursors.WaitCursor;
            DataTable table = ((DataSet)bindingSource.DataSource).Tables[bindingSource.DataMember];
            ToolStripTextBox tb = (ToolStripTextBox)sender;
            try
            {
                String filtro = "";
                foreach (DataColumn cl in table.Columns)
                {
                    if (this.ventanaBuscadorDataGridView.Columns[cl.ColumnName].Visible)
                    {
                        filtro += "ISNULL(" + cl.ColumnName.ToString() + ",'')+' '+";
                    }
                }
                filtro = filtro.Substring(0, filtro.Length - 5);
                filtro += " LIKE '%" + tb.Text + "%'";
                this.bindingSource.Filter = filtro;

                //MessageBox.Show(this.bindingSource.Count.ToString());
                //            MessageBox.Show(((DataSet)bindingSource.DataSource).Tables[bindingSource.DataMember].Rows.Count.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            Cursor.Current = Cursors.Default;
        }

        private void LimpiarToolStripButton_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                //this.bindingSource.RemoveFilter();
                this.BuscarToolStripTextBox.Text = string.Empty;
                this.textoRetorno = string.Empty;
                this.textoDescripcion = string.Empty;
                this.BuscarToolStripTextBox.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            Cursor.Current = Cursors.Default;
        }

        private void ventanaBuscadorDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            this.devolverResultado();
        }

        private void devolverResultado()
        {
            if (ventanaBuscadorDataGridView.CurrentRow==null)
            {
                return;
            }
            try { this.textoRetorno = this.ventanaBuscadorDataGridView.SelectedRows[0].Cells[this.columnaRetorno].Value.ToString(); }
            catch (Exception) { MessageBox.Show("La columna de retorno '" + this.columnaRetorno + "' No existe."); }
            try { this.textoDescripcion = this.ventanaBuscadorDataGridView.SelectedRows[0].Cells[this.columnaDescripcion].Value.ToString();}
            catch (Exception) { MessageBox.Show("La columna de Descripcion '"+this.columnaDescripcion+"' No existe.");}
            this.ok = true;
            this.Close();
        }

        private void VentanaBuscador_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                this.BuscarToolStripTextBox.Focus();
            }
        }

        
    }
}
